/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.exp;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

import who.tmap.bo.AttrDef;
import who.tmap.bo.Attrs;
import who.tmap.common.TMapException;
import who.tmap.dao.TMapDAOException;

public class CSVExportAdapter implements ExportAdapter {
	
    private static final String CSV_SEPARATOR =";";
	private static final String NEXT_LINE ="\r\n";	
	
	public CSVExportAdapter() {
	}
	
	@SuppressWarnings("unchecked")
	public void export( File file, Attrs attrs ) throws TMapException {	
			
        try {
			StringBuilder sb =new StringBuilder();
			
	        if ( attrs != null ) {
		        List<AttrDef> header =(List<AttrDef>)attrs.getHeader();
		        int colCt =0;
		        for( AttrDef attrDef : header ) {
		        	if ( ++colCt > 1 ) {
		        		sb.append( CSV_SEPARATOR );
		        	}
		            sb.append( attrDef.getName() );
		        }
		        
		        if ( colCt > 0 ) {
		        	sb.append( NEXT_LINE );
		        }
	        
		        Iterator it =attrs.getRows().iterator();
		        while( it.hasNext() ) {
		            List row =(List)it.next();
		            
		            colCt =0;
		            
		            Iterator it2 =row.iterator();
		            while( it2.hasNext() ) {
		                Object value =(Object)it2.next();
		                
			        	if ( ++colCt > 1 ) {
			        		sb.append( CSV_SEPARATOR );
			        	}
			        	
			        	if ( value != null ) {
			        		sb.append( value.toString() );
			        	} else {
			        		sb.append( "" );
			        	}
		            }
		            
		            if ( colCt > 0 ) {
		            	sb.append( NEXT_LINE );
		            }
		        }
	        }	
	        
	        BufferedWriter bw =new BufferedWriter( new FileWriter( file ) );
	        bw.write( sb.toString() );
	        bw.close();
        } catch( Exception e ) {
        	throw new TMapDAOException( e );
        }		
	}
}
